package status

import (
	"fmt"
	"time"

	"google.golang.org/grpc"
)

type StorageStatus struct {
	Machine         string
	DiskSize        uint64 // 服务器磁盘总空间
	DiskUsed        uint64 // 服务器磁盘占用空间
	DiskFree        uint64 // 服务器剩余空间
	CanCreateVolume bool
	Writeable       bool
	Volumes         []*VolumeStatus
	RpcConn         *grpc.ClientConn
	LastHeartbeat   int64
}

func NewStorageStatus(machine string, diskSize uint64, diskUsed uint64, diskFree uint64, canCreateVolume bool, volumes []*VolumeStatus, lastHeartbeat int64) *StorageStatus {
	return &StorageStatus{Machine: machine, DiskSize: diskSize, DiskUsed: diskUsed, DiskFree: diskFree, CanCreateVolume: canCreateVolume, Volumes: volumes, LastHeartbeat: lastHeartbeat}
}

func (vs *StorageStatus) IsAlive() bool {
	return time.Unix(vs.LastHeartbeat, 0).Add(maxAliveTime).After(time.Now())
}

func (vs *StorageStatus) IsAliveStr() string {
	if time.Unix(vs.LastHeartbeat, 0).Add(maxAliveTime).After(time.Now()) {
		if vs.Writeable {
			return "正常"
		} else {
			return "只读"
		}
	}
	return "离线"
}

func (vs *StorageStatus) DiskUsagePer() string {
	return fmt.Sprintf("%.2f", (float64(vs.DiskUsed)/float64(vs.DiskSize))*100) + "%"
}

func (vs *StorageStatus) GetSize(fileSize uint64) string {
	if fileSize < 1024 {
		return fmt.Sprintf("%.0fB", float64(fileSize)/float64(1))
	} else if fileSize < (1024 * 1024) {
		return fmt.Sprintf("%.1fKB", float64(fileSize)/float64(1024))
	} else if fileSize < (1024 * 1024 * 1024) {
		return fmt.Sprintf("%.1fMB", float64(fileSize)/float64(1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
	} else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
		return fmt.Sprintf("%.2fEB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
	}
}

func (vs *StorageStatus) VolumeUsed() string {
	var used uint64
	for _, vol := range vs.Volumes {
		used += vol.VolumeSize
	}
	return vs.GetSize(used)
}
